package com.conversationboard.view;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;

import org.joda.time.DateTime;

import com.conversationboard.config.Configuration;
import com.conversationboard.database.Database;
import com.conversationboard.database.Queries;
import com.conversationboard.model.User;

public class MonthsDisplay {

	private static Calendar startDate = new GregorianCalendar(2000, 1, 1);
	private static boolean gotStartDate = false;


	/**
	 * Constructor finds the date of the earliest thread in the database and sets that for the lifetime of the instance.
	 * 
	 * @throws SQLException
	 */

	public MonthsDisplay() throws SQLException {

		if (gotStartDate) {
			return;
		}

		synchronized (MonthsDisplay.class) {

			Connection connection = null;

			try {
				connection = Database.getConnection();

				PreparedStatement statement = connection.prepareStatement(Queries.GET_EARLIEST_THREAD);
				statement.execute();

				ResultSet resultSet = statement.getResultSet();

				String earliestThreadDate = null;

				while (resultSet.next()) {
					earliestThreadDate = resultSet.getString("timestamp");
				}

				String[] dateSections = earliestThreadDate.split("-");

				startDate = new GregorianCalendar(Integer.parseInt(dateSections[0]), Integer.parseInt(dateSections[1]) - 1, Integer.parseInt(dateSections[2]));

			} finally {
				gotStartDate = true;
				Database.close(connection);
			}
		}
	}


	/**
	 * @return HTML representing a list of hyperlinks representing months since
	 *         the site started.
	 */

	public String getMonths(User user) {

		DateTime date = new DateTime(startDate);
		StringBuilder buffer = new StringBuilder();
		Locale locale = user.getLocale();
		SimpleDateFormat dateFormat = new SimpleDateFormat("MMM yyyy", locale);

		buffer.append("<table width=\"100%\">");
		buffer.append("<td valign=\"top\" align=\"left\">");

		while (date.isBeforeNow()) {

			buffer.append("<a class=\"monthselection\" href=\"" + Configuration.getInstance().getRoot() + "/ThreadsInMonthControllerServlet?offset=0&year=" + date.getYear() + "&month=" + date.getMonthOfYear() + "\">" + dateFormat.format(date.toDate()) + "<br />");

			if (date.getMonthOfYear() == 12) {
				buffer.append("</td><td valign=\"top\" align=\"left\">");
			}

			date = date.plusMonths(1);
		}

		buffer.append("</td>");
		buffer.append("</table>");

		return buffer.toString();
	}

}
